package main

import (
	"fmt"
	"net/http"
	"strings"
	"log"
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"io/ioutil"
	"bytes"
	_"go_web_demo/models"
	"encoding/json"
	"go_web_demo/models"
	"go_web_demo/utils"
)

var db *sql.DB

func init() {
	db, _ = sql.Open("mysql", "root:password@tcp(127.0.0.1:3306)/blog?charset=utf8")
	db.SetMaxOpenConns(2000)
	db.SetMaxIdleConns(1000)
	db.Ping()
}
func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("---------login--------------")
	for k, v := range r.Form {
		fmt.Println("key:", k)
		fmt.Println("val:", strings.Join(v, ""))
	}
	fmt.Fprintf(w, "Hello astaxie!") //这个写入到w的是输出到客户端的
}

func register(w http.ResponseWriter, r *http.Request) {
	fmt.Println("---------register--------------")
	r.ParseForm()
	var user models.User
	result, err := ioutil.ReadAll(r.Body)
	if err!=nil {
		checkErr(err)
		return
	}
	fmt.Println("userName:  "+bytes.NewBuffer(result).String())
	 err = json.Unmarshal(result, &user)
	if err!=nil {
		checkErr(err)
	}else {
		fmt.Println(user)
		username := user.UserName
		password := user.Password
		fmt.Println("userName:  "+username)
		fmt.Println("password:  "+password)
		rows, err := db.Query("SELECT u_id FROM user where name = ?",username)
		if err!=nil {
			checkErr(err)
		}else {
			if rows.Next() {
				rows.Close()
				fmt.Println("-------用戶不存在--------")
				s := models.RegisterResult{
					Code:-1,
					Msg:"用戶已存在",
				}
				b, _ := json.Marshal(s)
				fmt.Fprintf(w, string(b)) //这个写入到w的是输出到客户端的
				return
			}else {
				rows.Close()
				fmt.Println("-------用戶不存在注册--------")
				stmt, err := db.Prepare("insert INTO user (u_id,name,password) values (?,?,?)")
				if err != nil {
					checkErr(err)
				}else {
					_, err := stmt.Exec(utils.UniqueId(), username, password)
					if err!=nil {
						checkErr(err)
					}else {
						s := models.RegisterResult{
							Code:0,
							Msg:"注冊成功",
						}
						b, _ := json.Marshal(s)
						fmt.Fprintf(w, string(b)) //这个写入到w的是输出到客户端的
						return
					}

				}
			}

		}
	}
	fmt.Fprintf(w, "error") //这个写入到w的是输出到客户端的


}
func checkErr(e error) {
	fmt.Println(e)
}
func notFound(w http.ResponseWriter, r *http.Request) {
	fmt.Println("---------notFound--------------")
	for k, v := range r.Form {
		fmt.Println("key:", k)
		fmt.Println("val:", strings.Join(v, ""))
	}
	fmt.Fprintf(w, "Hello astaxie!") //这个写入到w的是输出到客户端的
}
func httpRote(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
	w.Header().Set("Access-Control-Allow-Methods", "*")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE")
	if r.Method == "OPTIONS" {
		return
	}
	r.ParseForm()           //解析参数，默认是不会解析的
	fmt.Println(r.URL.Path) //这些信息是输出到服务器端的打印信息
	if r.Method == "GET" {
		switch r.URL.Path {
		case "/login":
			login(w, r)
			break
		default:
			notFound(w, r)

		}
	} else if r.Method == "POST" {
		switch r.URL.Path {
		case "/register":
			register(w, r)
			break
		default:
			notFound(w, r)
		}
	}

}

func main() {
	http.HandleFunc("/", httpRote)           //设置访问的路由
	err := http.ListenAndServe(":9090", nil) //设置监听的端口
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
